package com.zrrd.blog.wnb.controller;

import com.google.common.base.Preconditions;
import com.zrrd.blog.util.base.Result;
import com.zrrd.blog.util.tools.RequestUtil;
import com.zrrd.blog.wnb.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class AuthController {

    private static final String HEADER_TYPE = "Basic ";//有个空格

    @Autowired
    private ClientDetailsService clientDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthService authService;

    @GetMapping("/user/refreshToken")

    public Result refreshToken(HttpServletRequest request) {
        try {
            //获取请求中的刷新令牌
            String refreshToken = request.getParameter("refresh__token");
            Preconditions.checkArgument(StringUtils.isNotEmpty(refreshToken), "刷新令牌不能为空");
            //获取请求头
            String header = request.getHeader(HttpHeaders.AUTHORIZATION);
            if (header == null || !header.startsWith(HEADER_TYPE)) {
                throw new UnsupportedOperationException("请求头中没有client信息");
            }
            //解析请求头中的客户端信息
            String[] tokens = RequestUtil.extractAndDecodeHeader(header);
            assert tokens.length==2;
            String clientId = tokens[0];
            String clientSecret = tokens[1];
            //查询客户端信息，核对是否有效
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
            if (clientDetails == null) {
                throw new UnsupportedOperationException("clientId没有对应和的客户端");
            }
            //校验
            if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) {
                throw new UnsupportedOperationException("无效的clientSecret");
            }
            //获取新的认证信息
            return authService.refreshToken(header, refreshToken);
        }catch (Exception e){
            return Result.error("新令牌获取失败" + e.getMessage());
        }
    }
}
